package com.cuckoo.mall.thus.goodmultipledetail;


import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bgn.baseframe.base.MVPBaseActivity;
import com.bgn.baseframe.utils.BaseStringUtil;
import com.bgn.baseframe.utils.ToastUtil;
import com.bgn.baseframe.utils.UiUtil;
import com.bgn.baseframe.utils.evenbus.MainEvent;
import com.bgn.baseframe.utils.jsontool.GsonUtil;
import com.cuckoo.mall.R;
import com.cuckoo.mall.javabean.Product;
import com.cuckoo.mall.thus.manager.UserInfoManager;
import com.cuckoo.mall.thus.utils.DialogHelper;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */
@Route(path = "/mall/goodMultipleDetailActivity", group = "mall")
public class GoodMultipleDetailActivity extends MVPBaseActivity<GoodMultipleDetailContract.View, GoodMultipleDetailPresenter> implements GoodMultipleDetailContract.View {
    @BindView(R.id.rv_lunbo)
    RollPagerView rvLunbo;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_max_price)
    TextView tvMaxPrice;
    @BindView(R.id.tv_name)
    TextView tvTitle;
    @BindView(R.id.tv_select)
    TextView tvSelect;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.iv_cart)
    ImageView ivCart;
    @BindView(R.id.tv_add_cart)
    TextView tvAddCart;
    @BindView(R.id.tv_buy_now)
    TextView tvBuyNow;
    /*添加*/

    @BindView(R.id.iv_save)
    ImageView ivSave;

    @BindView(R.id.view_line1)
    View View_line1;
    @BindView(R.id.iv_back)
    ImageView ivBack;

    /*适配器*/
    private ImageAdapter topBannerAdapter;
    /*数据*/
    private Product goodInfo;
    /*数据*/
    @Autowired(name = "id")
    String productId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        setIsLoadTitleBar(false);
        setContentView(R.layout.activity_multiple_detail);
        ButterKnife.bind(this);
        initData();

    }

    private void initData() {
        if (isNetworkerConnectHint()) {
            showLoadingView();
            mPresenter.loadGoodsInfo(productId);
        } else {
            showDefaultView();
        }
    }

    @Override
    public void onDefaultViewClick(int tag) {
        if (isNetworkerConnectHint()) {
            hideDefaultView();
            initData();
        }
    }

    private void initWebView() {
        webview.getSettings().setDefaultTextEncodingName("UTF-8");
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.getSettings().setJavaScriptEnabled(true);
        // 开启DOM缓存，开启LocalStorage存储（html5的本地存储方式）
        webview.getSettings().setDomStorageEnabled(true);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                showDefaultView();

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                hideDefaultView();
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (isNetworkerConnectHint()) {
                    super.onPageStarted(view, url, favicon);
                } else {
                    showDefaultView();
                }

            }

//            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                handler.proceed(); // 接受证书
//            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                //Logger.d("错误：" + error.getDescription().toString() + "地址：" + view.getUrl());
                super.onReceivedError(view, request, error);

            }
        });
        //String css = "<style type=\"text/css\"> img {" + "width:100%;" + "height:auto;" + "}" + "body {" + "margin-right:15px;" + "margin-left:15px;" + "margin-top:15px;" + "}" + "</style>";
        String css = "<style type=\"text/css\"> img {" + "width:100%;" + "height:auto;" + "}" + "body {" + "margin-right:15px;" + "margin-left:15px;" + "margin-top:15px;" + "}" + "</style>";
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setLoadWithOverviewMode(true);
        String htmlString = goodInfo.getContent();
        htmlString = "<html><header>" + css + "</header><body>" + htmlString + "</body></html>";
        // webview.loadData(htmlString, "text/html", "utf-8");//部分手机这种写法会有乱码问题，用下面的
        webview.loadData(htmlString, "text/html; charset=UTF-8", null);

    }


    @OnClick({R.id.iv_back, R.id.iv_save, R.id.tv_select, R.id.iv_cart, R.id.tv_add_cart, R.id.tv_buy_now})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_save:
                if (UserInfoManager.getInstance().checkTrunLogin()) {
                    if (goodInfo == null) return;
                    if (goodInfo.getIs_favorite() == 1) {

                        if (isNetworkerConnectHint())
                            DialogHelper.showConfirmDialog(this, getString(R.string.sure_to_cancel_favorite), getString(R.string.confirm), getString(R.string.cancel), new DialogHelper.DialogPressCallBack() {
                                @Override
                                public void whenPressRightButton() {
                                    mPresenter.delFavorite(goodInfo.getProduct_id());
                                }
                            });
                    } else {

                        if (isNetworkerConnectHint())
                            mPresenter.addFavorite(goodInfo.getProduct_id());
                    }

                }
                break;

            case R.id.iv_cart:

                if (UserInfoManager.getInstance().checkTrunLogin()) {
                    ARouter.getInstance().build("/mall/cartActivity").navigation(this);
                    EventBus.getDefault().post(new MainEvent(MainEvent.UPDATE_CART));
                }
                break;
            case R.id.tv_select:
            case R.id.tv_add_cart:
                if (goodInfo == null) return;

                if (UserInfoManager.getInstance().checkTrunLogin()) {
//                    if (goodInfo.getAttribute_list() != null && goodInfo.getAttribute_list().size() > 0) {
//                        ARouter.getInstance().build("/mall/pickProductToCardActivity")
//                                //  .withTransition(R.anim.activity_bottom_in, R.anim.activity_bottom_in)
//                                .withString(JSON_STRING, GsonUtil.toJson(goodInfo)).navigation(this);
//                    } else {
//                        GoogleAnalyticsHelper.logAdd2Cart(this, goodInfo.getProduct_id(), 1);
//                        ApiManager.addToCart(goodInfo.getProduct_id(), 1, null).subscribe(new HttpObserver<TDataBean>(this) {
//                            @Override
//                            public void onSucceed(TDataBean value) {
//                                ToastUtil.showInfo(getString(R.string.addsuccessfully));
//                                EventBus.getDefault().post(new MainEvent(MainEvent.UPDATE_CART));
//                            }
//                        });
//                    }

                    // 时间2018年7月11日 14:00:51  产品当面确定 无论有没有属性，都开打挑选界面
                    ARouter.getInstance().build("/mall/pickProductToCardActivity")
                            //  .withTransition(R.anim.activity_bottom_in, R.anim.activity_bottom_in)
                            .withString(JSON_STRING, GsonUtil.toJson(goodInfo)).navigation(this);
                }
                break;
            case R.id.tv_buy_now:
                if (goodInfo == null) return;

                if (UserInfoManager.getInstance().checkTrunLogin()) {
                    ARouter.getInstance().build("/mall/pickProductToOrderActivity")
                            //  .withTransition(R.anim.activity_bottom_in, R.anim.activity_bottom_in)
                            .withString(JSON_STRING, GsonUtil.toJson(goodInfo)).navigation(this);
                }
                break;
        }
    }


    @Override
    public void whenGetGoodInfo(Product data) {
        goodInfo = data;
        handleBannerData(data.getBanners());
        initWebView();

        tvPrice.setText(data.getCurrency() + " " + BaseStringUtil.getPrioceFormatString(data.getPrice()));
        if (data.getMarket_price() != 0) {
            //tvMaxPrice.setText(Html.fromHtml("<strike>" + data.getCurrency() + " " + BaseStringUtil.getPrioceFormatString(data.getMarket_price()) + "</strike>"));
            tvMaxPrice.setText(BaseStringUtil.addDeleteLineToText(data.getCurrency() + " " + BaseStringUtil.getPrioceFormatString(data.getMarket_price())));
        } else {
            tvMaxPrice.setText("");
        }

        if (goodInfo.getAttribute_list() == null || goodInfo.getAttribute_list().size() == 0) {
            tvSelect.setVisibility(View.GONE);
            View_line1.setVisibility(View.GONE);
        }

        if (goodInfo.getIs_favorite() == 0) {
            ivSave.setImageResource(R.mipmap.save_no);
        } else {
            ivSave.setImageResource(R.mipmap.save_yes);
        }
        tvTitle.setText(data.getName());


    }

    @Override
    public void whenAddFavoriteSucceed() {
        ToastUtil.showInfo(getString(R.string.favorite_succeed));
        goodInfo.setIs_favorite(1);
        ivSave.setImageResource(R.mipmap.save_yes);
    }

    @Override
    public void whencancleFavoriteSucceed() {
        ToastUtil.showInfo(getString(R.string.move_success));
        goodInfo.setIs_favorite(0);
        ivSave.setImageResource(R.mipmap.save_no);
    }

    public void handleBannerData(List<String> images) {
        if (images == null) {
            return;
        } else {
            String[] datas = images.toArray(new String[images.size()]);
            rvLunbo.setHintView(new ColorPointHintView(getActivity(), UiUtil.getColor(com.bgn.baseframe.R.color.black_414141), UiUtil.getColor(com.bgn.baseframe.R.color.gray_c4c4c4)));
            rvLunbo.getLayoutParams().height = UiUtil.getScreenWidth() * 1 / 1;
            topBannerAdapter = new ImageAdapter(datas, getActivity(), rvLunbo);
            rvLunbo.setAdapter(topBannerAdapter);
            rvLunbo.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    //ToastUtil.showInfo(position + "");
                }
            });
            topBannerAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = webview.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webview);
            }
            webview.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webview.getSettings().setJavaScriptEnabled(false);
            webview.clearHistory();
            webview.clearView();
            webview.removeAllViews();
            webview.destroy();
        }
        super.onDestroy();
    }
}
